<template>
  <div>
    <el-tree
      ref="tree"
      node-key="id"
      show-checkbox
      default-expand-all
      :check-strictly="true"
      :data="list"
      :props="{label:'name',children:'children'}"
    />
    <el-row type="flex" justify="end" style="height: 40px; ">
      <el-button type="primary" @click="hSubmit"> 确定</el-button>
      <el-button type="info" @click="$emit('close')"> 取消</el-button>
    </el-row>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permissions'
import { transDataToTreeData } from '@/utils/index'
import { getRoleDetail, assignPerm } from '@/api/settings'

export default {
  props: {
    rowId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [] // 保存获取的权限
    }
  },
  created() {
    this.loadPermissionList()
  },
  methods: {
    // 获取权限
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        // console.log('getPermissionList', res)
        // 保存数据
        this.list = transDataToTreeData(res.data)
        // 获取当前角色所拥有的权限
        const info = await getRoleDetail(this.rowId)
        //  拥有的权限 info.data.permIds
        // console.log('用来获取当前员工拥有的权限', info)
        // 利用 tree 组件 把当前拥有的权限默认选中
        this.$refs.tree.setCheckedKeys(info.data.permIds)
      } catch (err) {
        console.log('getPermissionList', err)
      }
    },
    // 点击了确定
    async hSubmit() {
      try {
        // tree 组件 通过 key 获取被√选中的元素
        const permIds = this.$refs.tree.getCheckedKeys()
        await assignPerm({ id: this.rowId, permIds: permIds })
        // console.log('assignPerm', res)
        // 保存数据
        this.$emit('close') // 通知父组件关闭弹层
      } catch (err) {
        console.log('assignPerm', err)
      }
    }
  }
}
</script>

